#pragma once
#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
using namespace std;

using task_t=function<void()>;
static int number = 0;

void DownLoad()
{
    cout << "下载任务..., pid: " << getpid() << endl;
}
void Log()
{
    cout << "日志任务..., pid: " << getpid() << endl;
}
void Sql()
{
    cout << "数据库任务..., pid: " << getpid() << endl;
}

class TaskManage
{
public:
    TaskManage()
    {
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }
    ~TaskManage()
    {}

    void InsertTask(task_t task)
    {
        _tasks[number++] = task;
    }
    int SelectTask()
    {
        return rand() % number;
    }
    void ExecuteTask(int number)
    {
        if (_tasks.find(number) == _tasks.end())
        {
            return;
        }
        _tasks[number]();
    }
private:
    unordered_map<int, task_t> _tasks;
};

TaskManage TM;

void Worker()
{
    while (true)
    {
        int cmd = 0;
        int n = read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            TM.ExecuteTask(cmd);
        }
        else if(n == 0)
        {
            cout << "pid : " << getpid() << " quit.." << endl;
            break;
        }
    }
}
